package cn.itcalvin.sncoal.cth.component;

import cn.hutool.core.util.StrUtil;
import cn.itcalvin.sncoal.cth.config.MinioConfig;
import cn.itcalvin.sncoal.cth.exception.BusinessException;
import cn.itcalvin.sncoal.cth.pojo.response.minio.RespListFile;
import cn.itcalvin.sncoal.cth.pojo.response.minio.RespListFileItem;
import cn.itcalvin.sncoal.cth.utils.SnowFlakeUtils;
import io.minio.*;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import io.minio.errors.XmlParserException;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class MinioUtil {

    private  static MinioClient minioClient=null;

    /**
     * 初始化客户端
     */
    private static MinioClient getMinioClient() {
        if (minioClient == null) {
            try {
                minioClient = new MinioClient(MinioConfig.ENDPOINT, MinioConfig.ACCESS_KEY, MinioConfig.SECRET_KEY);
            } catch (InvalidEndpointException | InvalidPortException e) {
                log.error("初始化客户端失败", e);
                return null;
            }
        }
        return minioClient;
    }

    /**
     * 文件上传
     *
     * @param file 文件
     * @return Boolean
     */
    public String upload(String dicName, MultipartFile file,boolean isOriginalFileName) {
        String originalFilename = file.getOriginalFilename();
        if (StrUtil.isBlank(originalFilename)){
            throw new RuntimeException();
        }
        String fileName;
        if(isOriginalFileName){
            fileName = originalFilename;
        }else{
            fileName = SnowFlakeUtils.getId() + originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String objectName = dicName + "/" + fileName;
        try {
            final val putObjectOptions = new PutObjectOptions(file.getInputStream().available(), -1);
            putObjectOptions.setContentType(file.getContentType());
            //文件名称相同会覆盖
            getMinioClient().putObject(MinioConfig.BUCKET_NAME, objectName,
                    file.getInputStream(),putObjectOptions);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new BusinessException(e.getMessage());
        }
        return objectName;
    }

    /**
     * 预览图片
     * @param fileName
     * @return
     */
    public String preview(String fileName){
        // 查看文件地址
        try {
            String url = getMinioClient().presignedGetObject(MinioConfig.BUCKET_NAME,fileName);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 文件下载
     * @param fileName 文件名称
     * @param res response
     * @return Boolean
     */
    public void download(String fileName, HttpServletResponse res) {
        try (InputStream response = getMinioClient().getObject(MinioConfig.BUCKET_NAME,fileName)){
            byte[] buf = new byte[1024];
            int len;
            try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()){
                while ((len=response.read(buf))!=-1){
                    os.write(buf,0,len);
                }
                os.flush();
                byte[] bytes = os.toByteArray();
                res.setCharacterEncoding("utf-8");
                // 设置强制下载不打开
//                res.setContentType("application/force-download");
                res.setContentType("application/octet-stream");
                res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                try (ServletOutputStream stream = res.getOutputStream()){
                    stream.write(bytes);
                    stream.flush();
                }
            }
        } catch (Exception e) {
            log.error("文件下载失败", e);
        }
    }

    /**
     * 查看文件对象
     * @return 存储bucket内文件对象信息
     */
    public RespListFile listObjects(String prefix) {
        Iterable<Result<Item>> results = null;
        results = getMinioClient().listObjects(MinioConfig.BUCKET_NAME,prefix,false);
        RespListFile respListFile = new RespListFile();
        respListFile.setSearchPath(prefix);
        List<RespListFileItem> items = new ArrayList<>();
        try {
            for (Result<Item> result : results) {
                final val item = result.get();
                if(item.objectName().contains(".placeholder")){
                    continue;
                }
                items.add(new RespListFileItem(){{
                    final val split = item.objectName().split("/");
                    setFileName(split[split.length-1]);
                    setFileUrl(item.objectName());
                    setIsDir(item.isDir());
                    setSize(item.size());
                    if(!item.isDir()){
                        setLastModified(Date.from(item.lastModified().toInstant()));
                    }
                }});
            }
            respListFile.setFileList(items);
            return respListFile;
        } catch (Exception e) {
            log.error("获取存储bucket内文件对象信息失败", e);
            return null;
        }
    }


    /**
     * 删除
     * @param fileName
     * @return
     * @throws Exception
     */
    public boolean remove(String fileName){
        try {
            getMinioClient().removeObject( MinioConfig.BUCKET_NAME,fileName);
        }catch (Exception e){
            return false;
        }
        return true;
    }

}
